package com.shenzhenai.composesideeffects.samples

import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.delay

/**
 * @author huangzehui
 * @date 19/9/2025 下午10:47 周五
 * @description
 *
 *
 * 81-rememberUpdateState
 * https://www.bilibili.com/video/BV1ob4y1a7ad?spm_id_from=333.788.videopod.episodes&vd_source=e07cc8cc94eb22bd76722071b03cd199&p=81
 *
 *
 * 如果key值有更新，那么LaunchedEffect在重组时就会被重新启动。但是有时候需要
 * 在LaunchedEffect中使用最新的参数值，但是又不想重新启动LaunchedEffect，此时
 * 就需要用到rememberUpdatedState。
 *
 * rememberUpdatedState的作用是给某个参数创建一个引用，来跟踪这些参数，并保证
 * 其值被使用时是最新值，参数被改变时不重启effect。
 *
 *
 */

@Composable
fun LandingScreen(onTimeOut: () -> Unit) {
    val currentOnTimeOut by rememberUpdatedState(onTimeOut)

    LaunchedEffect(Unit, block = {
        Log.e("young_tesjkjdkf", "LaunchedEffect")

        repeat(10) {
            delay(1000L)
            Log.e("young_tesjkjdkf", "delay ${it + 1} s")
        }
        // 直接调用没办法改变，必须使用 rememberUpdatedState 包裹的，才可以动态改变
//        onTimeOut()
        currentOnTimeOut()
    })
}

@Composable
fun RememberUpdatedStateSample() {
    val onTimeOut1: () -> Unit = {
        Log.e("young_tesjkjdkf", "onTimeOut1")
    }

    val onTimeOut2: () -> Unit = {
        Log.e("young_tesjkjdkf", "onTimeOut2")
    }

    val changeOnTimeOutState = remember { mutableStateOf(onTimeOut1) }


    Column {
        Button(onClick = {
            if (changeOnTimeOutState.value == onTimeOut1) {
                changeOnTimeOutState.value = onTimeOut2
            } else {
                changeOnTimeOutState.value = onTimeOut1
            }
        }) {
            Text(text = "choose onTimeOut${if (changeOnTimeOutState.value == onTimeOut1) 1 else 2}")
        }


        LandingScreen(changeOnTimeOutState.value)
    }
}

@Preview
@Composable
fun RememberUpdatedStateSamplePreview() {
    RememberUpdatedStateSample()
}